import 'dart:async';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';

import '../../widget/common.dart';
import 'wechat_src/wechat_kit_platform_interface.dart';

const String kWechatAppID = 'wx51abe0a3849b13a1';
const String kWechatUniversalLink = 'https://api.ygxpt.com/autosteward/'; // iOS 请配置
const String kWechatAppSecret = '';
const String kWechatMiniAppID = '';

typedef Callback = void Function(dynamic);

class WechatManager {
  // 静态变量，用于保存单例实例
  static final WechatManager _singleton = WechatManager._internal();
  // 公开的静态方法，用于获取单例实例
  static WechatManager get instance { return _singleton; }

  static late Function(WeChatResponse) listener;

  // 私有构造函数，只能在类内部被调用
  WechatManager._internal() { debugPrint(""); }

  dispose() { }

  
  // 微信环境检查
  static cacheWechat() async {
    final install = await Fluwx().isWeChatInstalled;
    if (install == false) {
      showMessage("请安装微信");
    }
  }

  // 注册微信
  register() async {
    Fluwx().registerApi(appId: kWechatAppID, universalLink: kWechatUniversalLink).then((value) {
      if (value == true) {
        debugPrint("微信SDK注册成功！");
      }else {
        debugPrint("微信SDK注册失败！");
      }
    });
  }

  // 微信回调 - 冷启
  static handleInitial() {
    WechatKitPlatform.instance.handleInitialWXReq();
  }

  // 微信支付
  static Future<dynamic> wechatPay(var param,{Callback? result}) async {
    if(await cacheWechat() == false) {
      showMessage("请先安装微信");
      return;
    }
    // 添加订阅消息
    Fluwx().addSubscriber(listener = (response) {
      if (response is WeChatPaymentResponse) {
        // 调用传递的回调函数并传递 response
        if (result != null) { result(response); }
      }
      // 取消订阅消息
      Fluwx().removeSubscriber(listener);
    });
    Fluwx().pay(
      which: Payment(
      appId: param['appid'],
      partnerId: param['partnerid'],
      prepayId: param['prepayid'],
      packageValue: param['pkg'],
      nonceStr: param['noncestr'],
      timestamp: int.tryParse(param['timestamp']) ?? 0,
      sign: param['sign'],
    ));
  }

  // 文字分享 scene 0:聊天界面 1:朋友圈 2:收藏
  static shareText(WeChatScene scene, String text) {
    Fluwx().share(WeChatShareTextModel(text, scene: scene));
  }

  // 图片分享 scene 0:聊天界面 1:朋友圈 2:收藏
  static shareImage(WeChatScene scene, String url) {
    Fluwx().share(WeChatShareImageModel(WeChatImage.network(url), scene: scene));
  }

  // 网页分享 scene 0:聊天界面 1:朋友圈 2:收藏
  static shareWebpage(WeChatScene scene, String url, String thumbnail, String desc) {
    Fluwx().share(WeChatShareWebPageModel(url, thumbnail: WeChatImage.network(thumbnail), description: desc, scene: scene));
  }

  // 打开微信小程序
  static openMiniProgram(var url) async {
    if(await cacheWechat()) {
      var name = url.replaceAll("open.wechat://", "");
      Fluwx().open(target: MiniProgram(username: name));
    }else {
      showMessage("请先安装微信");
      return;
    }
  }

}
